<?php
include_once('include/Config.php');
include_once('entities/Usuario.php');

Class TableEntityDAL {

    private $link;
    
    public $tablename;
    public $columns = Array();
    public $cantidadFilas = 0;
    public $cantidadFilasXml = 0;
    
    public $result;
    public $errorDesc;


    public function __construct($tableName = "") {
        $this->tablename = $tableName;
        $this->conectar();
    }

    private function conectar() {
        
        //Tomado del config.php 
        $this->link = $GLOBALS["DBConnPDO"];
        
    }

    public function obtenerRegistros($tableName = "")
    {
    	return( $this->obtenerRegistrosFiltro(" WHERE 1 ", $tableName));
    }
    
    public function obtenerRegistrosFiltro($param, $tableName = "") {
    	  
    	  $tableName = $this->validarTabla($tableName);
    	  
    	  if(count($this->columns) == 0) 
    	  {
    	  	$this->columns = $this->obtenerColumnasTabla($tableName);
    	  	//echo "columnas ==> <pre>"; print_r($this->columns); echo "</pre>";
    	  }
    	  
    	  $this->cantidadFilas = 0;
    	  
    	  $sqlFields = $this->obtenerListadoCampos();
    	  
    	  $sql = "SELECT " . $sqlFields . " FROM `" . $tableName . "` " . $param;
        $listaRegistros = array();

        foreach ($this->link->query($sql) as $rowData) {

            $registro = Array();
            
            $registro = $this->asignarPorColumna($rowData);
            
            $listaRegistros [] = $registro;
            
            $this->cantidadFilas ++;
        }
        
        return $listaRegistros;
    }
    
    public function obtenerRegistrosFormatoXml($param = "", $tableName = "", $numRowsXPage = 20) {
    	  
    	  $tableName = $this->validarTabla($tableName);
    	  
    	  if(count($this->columns) == 0) 
    	  {
    	  	$this->columns = $this->obtenerColumnasTabla($tableName);
    	  	//echo "columnas ==> <pre>"; print_r($this->columns); echo "</pre>";
    	  }
    	  
    	  $this->cantidadFilasXml = 0;
    	  
    	  $primaryKey = "idCliente";//getPrimaryKeyFromTableDef();
    	  
    	  $sqlFields = $this->obtenerListadoCampos();
    	  
    	  $sql = "SELECT " . $sqlFields . " FROM `" . $tableName . "` " . $param;

        $xmlOutFilas = "";

        foreach ($this->link->query($sql) as $rowData) {
        
            $xmlOutFilas .= "<row id='" . $rowData[$primaryKey] . "'>";
            
            for ($ivar = 0; $ivar < count($this->columns); $ivar ++) 
            {
		    	  	$colName = $this->columns[$ivar]["Field"];
		    	  	$xmlOutFilas .= "<cell>" . $rowData[$colName] . "</cell>";
		    	  }
            
            $this->cantidadFilasXml ++;
            
            $xmlOutFilas .= "</row>\n";
        }
        
        //Genero la salida 
        $count = $this->cantidadFilasXml;
        $page = 1;
        
        if ($count > 0 && $numRowsXPage > 0) {
            $total_pages = ceil($count / $numRowsXPage);
        } else {
            $total_pages = 0;
        }
        
        if ($page > $total_pages)
            $page = $total_pages;
        
        $start = $numRowsXPage * $page - $numRowsXPage;
        
        if ($start < 0)
            $start = 0;

        $xmlOut = "<?xml version='1.0' encoding='utf-8'?>\n";
        $xmlOut .= "<rows>\n";
        $xmlOut .= "<page>" . $page . "</page>\n";
        $xmlOut .= "<total>" . $total_pages . "</total>\n";
        $xmlOut .= "<records>" . $count . "</records>\n";
        $xmlOut .= $xmlOutFilas;
        $xmlOut .= "</rows>\n";
        
        return $xmlOut;
    }

    public function obtenerColumnasTabla($tableName = "") {
        $sql = "DESCRIBE `" . $tableName . "`; ";
        $listaCampos = array();
        //
        // INFO 
        // http://dev.mysql.com/doc/refman/5.0/en/getting-information.html
        //
        // http://www.prodevtips.com/2010/11/04/generating-extended-mysql-inserts-in-php/
        //
        try
        {		
		        foreach ($this->link->query($sql) as $row) {
		
		            $campo = Array();
		            
		            $campo["Field"] = $row['Field'];
		            $campo["Type"] = $row['Type'];
		            $campo["Null"] = $row['Null'];
		            $campo["Key"] = $row['Key'];
		            $campo["Default"] = $row['Default'];
		            $campo["Extra"] = $row['Extra'];
		            
		            $listaCampos [] = $campo;
		        }
		        
		        $this->result = 0;
            $this->errorDesc = "";
		        return $listaCampos;
		        
		    } catch (PDOException $e) {
            $this->result = -1;
            $this->errorDesc = $e->getMessage();
            return Array();
        }
    }

    public function obtenerListadoCampos() {
    	  $sqlFields = "";
    	  $cantidad = count($this->columns);
    	  $cont = 0;
    	  
    	  for ($ivar = 0; $ivar < count($this->columns); $ivar ++) {
    	  	$arrColumna = $this->columns[$ivar];
    	  	
    	  	$sqlFields .= "`" . $arrColumna["Field"] . "`"; //$arrColumna["Field"]
    	  	$cont ++;
    	  	
    	  	if($cont < $cantidad) $sqlFields .= ", ";
    	  }
    	  return $sqlFields;
    }


    public function asignarPorColumna($rowData) {
    		$registroOut = array();
    		
        for ($ivar = 0; $ivar < count($this->columns); $ivar ++) {
    	  	$colName = $this->columns[$ivar]["Field"];
    	  	$registroOut[$colName] = $rowData[$colName];
    	  }
        
    	  return $registroOut;
    }
   
    public function validarTabla($tableName = "") {
    		
    		$salida = $this->tablename;
    		
    		if($tableName != "") $salida = $tableName;
    		        
    	  return $salida;
    }
     
    public function cantidadFilas() {    		        
    	  return $this->cantidadFilas;
    }
     
    public function cantidadFilasXml() {    		        
    	  return $this->cantidadFilasXml;
    }
     
    public function insertarNuevoUsuario($usuario) {

        try {
           	$sqlInsert = "INSERT INTO `usuario` ( NickName, Password, NombreApellido, DNI, Email, idEmpresa, isAdmin, isBorrado) " . 
            		" VALUES (:NickName, :Password, :NombreApellido, :DNI, :Email, :idEmpresa, :isAdmin, :isBorrado );";
           
            $stmt = $this->link->prepare($sqlInsert);
            $nickname = $usuario->getNickName();
            $password = $usuario->getPassword();
            $nombreapel = $usuario->getNombreApellido();
            $dni = $usuario->getDni();
            $email = $usuario->getMail();
            $idEmpresa = $usuario->getIdEmpresa();
            $isAdmin = $usuario->getIsAdmin();
            $isBorrado = $usuario->getIsBorrado();
            
            $stmt->bindParam(':NickName', $nickname, PDO::PARAM_STR, 100);
            $stmt->bindParam(':Password', $password, PDO::PARAM_STR, 100);
            $stmt->bindParam(':NombreApellido', $nombreapel, PDO::PARAM_STR);
            $stmt->bindParam(':DNI', $dni, PDO::PARAM_STR);
            $stmt->bindParam(':Email', $email, PDO::PARAM_STR);
            $stmt->bindParam(':idEmpresa', $idEmpresa, PDO::PARAM_STR);
            $stmt->bindParam(':isAdmin', $isAdmin, PDO::PARAM_BOOL);
            $stmt->bindParam(':isBorrado', $isBorrado, PDO::PARAM_BOOL);

            $stmt->execute();

            $this->result = 0;
            $this->errorDesc = "";
            return $this->link->lastInsertId();
            
        } catch (PDOException $e) {
            $this->result = -1;
            $this->errorDesc = $e->getMessage();
            return $this->result;
        }
    }

    public function bajaUsuario($usuario) {

        try {
            $stmt = $this->link->prepare('DELETE from `usuario` where idUsuario = :idUsuario;');
            $idUsuario = $usuario->getIdUsuario();
            $stmt->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
            $stmt->execute();
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

    public function modificarUsuario($usuario) {

        try {
        		$sqlUpdate = "UPDATE usuario SET NickName = :NickName, Password = :Password, NombreApellido = :NombreApellido, DNI = :DNI, Email = :Email, idEmpresa = :idEmpresa, isAdmin = :isAdmin  WHERE idUsuario = :idUsuario;";
            $stmt = $this->link->prepare($sqlUpdate);
            $idUsuario = $usuario->getIdUsuario();
            $nickname = $usuario->getNickName();
            $password = $usuario->getPassword();
            $nombreapel = $usuario->getNombreApellido();
            $dni = $usuario->getDni();
            $email = $usuario->getMail();
            $idEmpresa = $usuario->getIdEmpresa();
            $isAdmin = $usuario->getIsAdmin();
            $isBorrado = $usuario->getIsBorrado();

            $stmt->bindParam(':NickName', $nickname, PDO::PARAM_STR, 100);
            $stmt->bindParam(':Password', $password, PDO::PARAM_STR, 100);
            $stmt->bindParam(':NombreApellido', $nombreapel, PDO::PARAM_STR);
            $stmt->bindParam(':DNI', $dni, PDO::PARAM_STR);
            $stmt->bindParam(':Email', $email, PDO::PARAM_STR);
            $stmt->bindParam(':idEmpresa', $idEmpresa, PDO::PARAM_STR);
            $stmt->bindParam(':isAdmin', $isAdmin, PDO::PARAM_BOOL);
            $stmt->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
            $stmt->execute();
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

}

?>